package com.tianchi.lexiang.background;

import java.io.File;

import com.tianchi.lexiang.R;
import com.tianchi.lexiang.background.util.Readsmb;
import com.tianchi.lexiang.bean.LeXiangConstants;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.EthernetManager;
import android.os.AsyncTask;
import android.os.StatFs;
import android.provider.Settings;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LanAddSongIPSetting implements android.view.View.OnClickListener {
	
	private static final String TAG = "LanAddSongIPSetting";
	public static final String STATIC_IPPERSIST_KEYS ="staticIPPersistKeys";
	public static final String STATIC_BACKUP = "network_config";
	public static final String CLOSE_ETHERNET_ACTION = "close_ethernet_action";
	
	private EthernetManager mEthernetManager;
	private SharedPreferences pref;
	
	private static LanAddSongIPSetting instance = null;
	private String[] staticIPPersistKeys = {"ethernet_static_ip" , "ethernet_static_netmask" , "ethernet_static_gateway" , "ethernet_static_dns1"};
	private String[] staticNetConfig = new String[4];
	
	private static final String songSmbMachine = "smb://192.168.6.100/TCTOOL/jywjg.xls";
	private static final String singerSmbMachine = "smb://192.168.6.100/TCTOOL/singer/";
	private static final String localpath = "hdd1/";
	public static final String localTemporaryFolder = "hdd1/temporarySingerFolder/";
	
	private Context mContext;
	private View myView;
	private Dialog myDialog;
	
	private EditText ipFourth;
	private Button saveBtn;
	private Button cancleBtn;
	
	private ProgressDialog mProgressDialog;
	private Readsmb readsmb;
	
	private long residualSize;
	private long canAddSongNum;
	
	private String type;
	
	private LanAddSongIPSetting(){
		
	}
	
	public static LanAddSongIPSetting getInstance(){
		if(instance == null){
			instance = new LanAddSongIPSetting();
		}
		return instance;
	}
	
	public void openDialog(Context mContext,String type){
		this.mContext = mContext;
		this.type = type;
		LayoutInflater factory = LayoutInflater.from(mContext);
		myView = factory.inflate(R.layout.lan_add_song_ipsetting, null);
		ipFourth = (EditText)myView.findViewById(R.id.ip_fourth);
		ipFourth.setInputType(EditorInfo.TYPE_CLASS_PHONE);
		ipFourth.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});
		
		saveBtn = (Button)myView.findViewById(R.id.save_btn);
		saveBtn.setOnClickListener(this);
		cancleBtn = (Button)myView.findViewById(R.id.cancel_btn);
		cancleBtn.setOnClickListener(this);
		
		myDialog = new Dialog(myView.getContext());
		myDialog.setTitle(R.string.ip_setting);
		myDialog.setContentView(myView);
		myDialog.getWindow().setLayout(600, 200);
		myDialog.show();
		mEthernetManager = (EthernetManager) mContext.getSystemService(Context.ETHERNET_SERVICE);
		pref = mContext.getSharedPreferences(STATIC_BACKUP, Context.MODE_WORLD_READABLE);
		readsmb = Readsmb.getINstance();
	}

	@Override
	public void onClick(View view) {
		
		int id = view.getId();
		switch (id) {
		case R.id.save_btn:
			if(ipFourth.getText().toString() != null && !"".equals(ipFourth.getText().toString())){
				int ipFouethStr = Integer.parseInt(ipFourth.getText().toString());
				if(ipFouethStr == 100 || ipFouethStr<= 0 || ipFouethStr > 255){
					toastDialog(mContext.getString(R.string.ip_not_setting_one_hundred));
					
				} else {
					staticNetConfig[0] = "192.168.6." + ipFouethStr;
					staticNetConfig[1] = "255.255.255.0";
					staticNetConfig[2] = "192.168.6.1";
					staticNetConfig[3] = "192.168.6.1";
					Log.d(TAG, "[ethernetEnable]");
					mEthernetManager.setEthernetEnabled(true);
					Settings.System.putInt(mContext.getContentResolver(), "ethernet_use_static_ip", 1);
					int length = staticNetConfig.length;
					for (int i = 0; i < length; i++) {
						String value = staticNetConfig[i];
						Log.d(TAG, "[onClick]......value===>" + value);
						pref.edit().putString(staticIPPersistKeys[i], value).commit();
						Settings.System.putString(mContext.getContentResolver(), staticIPPersistKeys[i], value);
					}
					mProgressDialog = ProgressDialog.show(mContext, mContext.getString(R.string.are_download), mContext.getString(R.string.download_in), true);
					if(NetworkAddSong.NETWORK_ADD_SONG.equals(type)){
						new SynchronousSongData().execute();
					}else{
						new SynchronousSingerData().execute();
					}
				}
			}else{
				toastDialog(mContext.getString(R.string.ip_not_empty));
			}
			break;
		case R.id.cancel_btn:
			myDialog.dismiss();
			break;

		default:
			break;
		}
		
	}
	
	public class SynchronousSongData extends AsyncTask<String, String, Boolean>{

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@Override
		protected Boolean doInBackground(String... arg0) {
			Boolean bool = readsmb.readFromSmb(songSmbMachine, localpath) ;
			Log.d(TAG, "[SynchronousData]....bool====>" + bool);
			if(bool && canAddNumberSong()){
				return true;
			}
			return false;
		}
		
		@Override
		protected void onProgressUpdate(String... arg0) {
			super.onProgressUpdate(arg0);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			Log.d(TAG, "[SynchronousData]...result===>" + result);
			if(result){
				myDialog.dismiss();
				Intent intent = new Intent();
				intent.putExtra(UdiskAddsong.RESIDUAL_SIZE, residualSize);
				intent.putExtra(UdiskAddsong.CAN_ADD_SONG_NUM, canAddSongNum);
				intent.setClass(mContext, LanAddSong.class);
				mContext.startActivity(intent);
			}else{
				toastDialog(mContext.getString(R.string.lan_synchronous_data_failure));
			}
			mProgressDialog.dismiss();
		}
	}
	
	private class SynchronousSingerData extends AsyncTask<String, String, Boolean>{

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@Override
		protected Boolean doInBackground(String... arg0) {
			 Boolean bool = readsmb.readSingerFromSmb(singerSmbMachine,localTemporaryFolder);
			 if(bool){
				 return true;
			 }else{
				 return false;
			 }
			
		}
		
		@Override
		protected void onProgressUpdate(String... arg0) {
			super.onProgressUpdate(arg0);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if(result){
				myDialog.dismiss();
				Intent intent = new Intent();
				intent.setClass(mContext, LanAddSinger.class);
				mContext.startActivity(intent);
			}else{
				toastDialog(mContext.getString(R.string.lan_add_singer_tip));
			}
			mProgressDialog.dismiss();
		}
		
	}
	
	private Boolean canAddNumberSong(){
		File file = new File(LeXiangConstants.SONG_HARD_DISK_PATH);
		if(file.exists()){
			StatFs sf = new StatFs(LeXiangConstants.SONG_HARD_DISK_PATH);
			long blockSize = sf.getBlockSize();
			long availCount = sf.getAvailableBlocks();
			residualSize = availCount * blockSize / 1024 / 1024 / 1024;
			canAddSongNum = (residualSize * 1024) / 60;
			return true;
		}else{
			return false;
		}
	}
	
	private void toastDialog(String message){
		Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
	}
}
